package async;

import jdk.internal.vm.Continuation;
import jdk.internal.vm.ContinuationScope;

// java --add-opens java.base/jdk.internal.vm=ALL-UNNAMED -Xlog:gc=info,gc+heap=info:gc_loom.log:time async.Loom3Test
// 1082 ms, r = 4995000000
public class Loom3Test {
	private static final int N1 = 100;
	private static final int N2 = 100;
	private static final int N3 = 1000;
	private static final int N = N1 * N2 * N3;
	private static int s_i;
	private static final ContinuationScope cs = new ContinuationScope("VirtualThreads");

	private static void f3() {
		for (int i = 0; i < N3; i++) {
			s_i = i;
			Continuation.yield(cs);
		}
	}

	private static void f2() {
		for (int i = 0; i < N2; i++)
			f3();
	}

	private static void f1() {
		for (int i = 0; i < N1; i++)
			f2();
	}

	public static void main(String[] args) {
		long t = System.nanoTime();
		var c = new Continuation(cs, Loom3Test::f1);
		long r = 0;
		for (int i = 0; i < N; ++i) {
			c.run();
			r += s_i;
		}
		System.out.println((System.nanoTime() - t) / 1_000_000 + " ms, r = " + r);
	}
}
